package cn.tedu.rabbitmq.topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

//模拟主题模式中的消费者
public class TopicConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂，并设置连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1"); //设置主机
        cf.setPort(5672); //客户端连接服务端的端口号，默认是5672，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.建立连接
        Connection nc = cf.newConnection();
        //3.在连接创建channel
        Channel cc = nc.createChannel();
        //4.创建队列的无参方法，本身就是一个随机、非持久、独占的、自动删除的队列
        String queueName = cc.queueDeclare().getQueue();
        //5.定义交换机
        cc.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);
        //6.需要使用绑定键来绑定交换机和队列
        System.out.print("输入绑定键,用空格隔开:");
        String str = new Scanner(System.in).nextLine();//aaa bbb ccc
        String[] bingDingKeys = str.split("\\s+");
        for (String bingDingKey : bingDingKeys) {
            cc.queueBind(queueName,"topic_logs",bingDingKey);
        }
        //7.消费消息
        //处理消息的回调函数
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery message) throws IOException {
                //Delivery中有我们要消费的信息
                byte[] a = message.getBody();
                String msg = new String(a);
                System.out.println("收到"+msg);
                System.out.println("消息处理完毕");
            }
        };
        //取消接收时的回调函数
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {
            }
        };
        cc.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }
}
